<?php 

	class tool{

		public $appid = "wx9794cfc617379395";//测试号
		//public $appid = "wxb7a52b78c7a3b606";
		public $secret = "c02fd73d7c52cfd3ebb4c63cdba0f3c1";//测试号
		//public $secret = "ca823db99614ad3a20c5b7452bc1f9a7";
		public function gettoken(){
			
			$redis = new Redis;
			$redis -> connect("94.191.70.89","6379");
			$redis -> auth("123123");
			if($redis->get('token')){
				return $redis->get('token');
			}
			$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
			$re = $this->httpCurl($url);
			$re = json_decode($re,true);
			if(isset($re['access_token'])){
				$redis -> set('token',$re['access_token'],$re['expires_in']-200);
				return $re['access_token'];
			}else{
				return false;
			}
		}

		public function conRedis(){
			$redis = new Redis;
			$redis->connect('94.191.70.89','6379');
			$redis->auth('123123');
			return $redis;
		}

		public function createMenu(){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token;
			$data = [
				"button"=>[
					[
						'name'=>'每日热门视频',
						'type'=>'view',
						'url'=>'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9794cfc617379395&redirect_uri=http://lx.medequle.xyz/auth.php&response_type=code&scope=snsapi_userinfo&state=666#wechat_redirect',
					],
					[
						'name'=>'music',
						'sub_button'=>[
	                        [
	                            'name'=>'热门摇滚榜单',
	                            'type'=>'click',
	                            'key'=>'yg01'
	                        ],
	                        [
	                            'name'=>'热门流行榜单',
	                            'type'=>'click',
	                            'key'=>'yg02'
	                        ],
		                ]
					],
					[
						'name'=>'发送位置',
						'type'=>'location_select',
						'key'=>'third003',
					],
				]
			];
			$data = json_encode($data,JSON_UNESCAPED_UNICODE);
			$re = $this->httpCurl($url,"POST",$data);
			var_dump($re);
		}

		//删除菜单
		public function delMenu(){
			$token = $this->gettoken();
			$url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$token;
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$re = $this->httpCurl($url);
			var_dump($re);
		}

		public function httpCurl($url,$type='GET',$data=[]){
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
			if($type == "POST"){
				curl_setopt($ch,CURLOPT_POST,true);
				curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
			}
			$re = curl_exec($ch);
			curl_close($ch);
			return $re;
		}

		public function uploadImg(){

			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=image";//临时
			//$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=image";//永久
			$data=[
				'media'=>new cURLFILE('1.jpg')
			];
			$re = $this->httpCurl($url,"POST",$data);
			var_dump($re);
		}

		public function uploadVideo(){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=video";
			$desc = [
				'title'=>'视频标题',
				'introduction'=>'视频介绍'

			];
			$data=[
				'media'=>new cURLFILE('l1.mp4'),
				'description'=> json_encode($desc,JSON_UNESCAPED_UNICODE)
			];
			$re = $this->httpCurl($url,"POST",$data);
			var_dump($re);
		}

		public function getImg($mediaid){
			header('content-type:image/png');
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url="https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$mediaid;
			echo $re = $this->httpCurl($url);
		}

		public function getVideo($mediaid){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$token;
			$data = [
				'media_id'=> $mediaid
			];
			echo $re = $this->httpCurl($url,"POST",json_encode($data,JSON_UNESCAPED_UNICODE));
		}

		public function getall($type){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$token;
			$data = [
				'type'   => $type,
				'offset' => 0,
				'count'  =>20
			];
			echo $re = $this->httpCurl($url,"POST",json_encode($data,JSON_UNESCAPED_UNICODE));
		}

		public function delEver($mediaid){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=".$token;
			$data = [
				'media_id'=> $mediaid
			];
			echo $re = $this->httpCurl($url,"POST",json_encode($data,JSON_UNESCAPED_UNICODE));

		}

		public function customSerSend(){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;
			// $data = [
			// 	"touser"=>'oXApi1prWkoORbUPG362OA1VHoIU',
			// 	'msgtype'=>'text',
			// 	'text'=>[
			// 		'content'=>'test',
			// 	],
			// ];
			//满意度菜单
			$data = [
				"touser"=>'oXApi1prWkoORbUPG362OA1VHoIU',
				'msgtype'=>'msgmenu',
				'msgmenu'=>[
					'head_content'=>'您对本次服务是否满意呢?',
					'list'        =>[
						[
							'id'=>'1',
							'content'=>'非常满意'
						],
						[
							'id'=>'2',
							'content'=>'满意'
						],
						[
							'id'=>'3',
							'content'=>'一般'
						],
						[
							'id'=>'4',
							'content'=>'不满意'
						],
						[
							'id'=>'5',
							'content'=>'非常不满意'
						],
						
					],
					'tail_content'=>'欢迎再次光临'
				],
			];
			echo $re = $this->httpCurl($url,"POST",json_encode($data,JSON_UNESCAPED_UNICODE));
		}

		public function massSend(){
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$token;
			$data = [
				'touser' => [
					'oXApi1prWkoORbUPG362OA1VHoIU',
					'oXApi1ptYt1az84x9b5z7YPasAzA',
				],
				'msgtype'=>'text',
				'text'=>[
					'content'=>'群发test',
				]
			];
			echo $re = $this->httpCurl($url,"POST",json_encode($data,JSON_UNESCAPED_UNICODE));
		}

		public function getTicket($scene_id,$type='QR_SCENE',$expire=0){
			$redis = $this->conRedis();
			if($redis->get('ticket:'.$type.":".$scene_id)){
				return $redis->get('ticket:'.$type.":".$scene_id);
			}
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token;
			switch ($type) {
				case 'QR_SCENE':
					$data = [
						'expire_seconds' => $expire,
						'action_name'    => $type,
						'action_info'    => [
							'scene' => [
								'scene_id'=> $scene_id
							]
						]
					];
				break;
				
				case 'QR_LIMIT_SCENE':
					$data = [
						'action_name'    => $type,
						'action_info'    => [
							'scene' => [
								'scene_id'=> $scene_id
							]
						]
					];
				break;
			}
			$data = json_encode($data,JSON_UNESCAPED_UNICODE);
			$re = $this->httpCurl($url,'POST',$data);
			$re = json_decode($re,true);
			if($expire>0){
				$redis->set('ticket:'.$type.":".$scene_id,$re['ticket'],$expire);
			}else{
				$redis->set('ticket:'.$type.":".$scene_id,$re['ticket']);
			}
			return $re['ticket'];
		}

		public function getCode(){
			header('content-type:image/png');
			$ticket = $this->getTicket('12138',"QR_SCENE",60);
			$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
			echo $this->httpCurl($url);
		}

		private function getJsApiTicket() {
			// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
			$redis = $this->conRedis();
			if($redis->get('jsapi_ticket')){
				return $redis->get('jsapi_ticket');
			}
			$token = $this->gettoken();
			if(!$token){
				return json_encode(['error'=>'token没有']);
			}
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$token;
			$re = json_decode($this->httpCurl($url));	
			$redis->set('jsapi_ticket',$re->ticket,7000);
			return $re->ticket;
		}

		private function createNonceStr($length = 16) {
			$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			$str = "";
			for ($i = 0; $i < $length; $i++) {
				$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
			}
			return $str;
		}

		public function getSignPackage() {
			$jsapiTicket = $this->getJsApiTicket();

			// 注意 URL 一定要动态获取，不能 hardcode.
			$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
			$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

			$timestamp = time();
			$nonceStr = $this->createNonceStr();

			// 这里参数的顺序要按照 key 值 ASCII 码升序排序
			$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

			$signature = sha1($string);

			$signPackage = array(
				"appId"     => $this->appid,
				"nonceStr"  => $nonceStr,
				"timestamp" => $timestamp,
				"url"       => $url,
				"signature" => $signature,
				"rawString" => $string
			);
			return $signPackage; 
		}
	}
	// (new tool)->createMenu();
	//$mediaid = "gQFJggSKv2iGltwyW-yo8c0PnWldbhq3xk0AQEmuXCmpoU8KITOCPfH9-uc-v4of";//临时素材--图片
	//(new tool)->getImg($mediaid);
	//(new tool)->uploadVideo();
	// $mediaid = "kVOvRUAp8hCVY4l7XA3d_wyhSdOY-9DEymVtjiUUv8w";//永久素材--视频
	// (new tool)->getVideo($mediaid);
	//(new tool)->getall('video');
	// (new tool)->customSerSend();
	// (new tool)->getCode();
	


